package com.wengyingjian.weixin.qq;

import com.scienjus.smartqq.callback.MessageCallback;
import com.scienjus.smartqq.client.SmartQQClient;
import com.scienjus.smartqq.model.*;
import com.wengyingjian.kylin.util.StringUtil;
import com.wengyingjian.weixin.common.model.TbkUrlTransferRecord;
import com.wengyingjian.weixin.dao.TbkUrlTransferDao;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * Created by wengyingjian on 16/12/26.
 * <p>
 * v1.0：先不考虑并发的问题，假设所有的返回结果与请求都按发送顺序一一对应
 */
@Service
public class QQ2AlimamaService {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    // 2978753907 -> 3023782116
    // 3385663975 -> 412737442
    private static long tbk_qq_machine_id = 0L;

    private SmartQQClient client;

    @Autowired
    private TbkUrlTransferDao tbkUrlTransferDao;

    /**
     * 1.提交查询
     *
     * @param url
     */
    public void sendMsg(String url) {
        client.sendMessageToFriend(tbk_qq_machine_id, url);
        logger.info("QQ2AlimamaService.sendMsg: url={}", url);
    }

    {

        new Thread() {
            @Override
            public void run() {
                client = new SmartQQClient(new MessageCallback() {
                    @Override
                    public void onMessage(SmartQQClient smartQQClient, Message message) {
                        logger.info("SmartQQClient.onMessage: userId={},content={}", message.getUserId(),
                                message.getContent());
                        if (message.getUserId() != tbk_qq_machine_id) {
                            return;
                        }
                        // 处理返回结果
                        handleQQMessageResult(message.getContent());
                    }

                    @Override
                    public void onGroupMessage(SmartQQClient smartQQClient, GroupMessage groupMessage) {

                    }

                    @Override
                    public void onDiscussMessage(SmartQQClient smartQQClient, DiscussMessage discussMessage) {

                    }
                });
                List<Category> categories = client.getFriendListWithCategory();
                for (Category category : categories) {
                    List<Friend> fd = category.getFriends();
                    for (Friend f : fd) {
                        if ("1".equals(category.getName())) {
                            tbk_qq_machine_id = f.getUserId();
                            logger.info("friend:{},group={}", f, category);
                        }
                    }
                }
                if (tbk_qq_machine_id == 0L) {
                    try {
                        client.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    throw new RuntimeException("获取机器人信息失败，推出程序");
                }

            }
        }.start();
        // ThreadHolder.executor.submit(new Runnable() {
        //
        // });

    }

    private void handleQQMessageResult(String content) {
        String title = getTitle(content);
        TbkUrlTransferRecord record = tbkUrlTransferDao.selectByTitle(title);
        if (record == null) {
            throw new RuntimeException("收到机器人的QQ消息时无法找到top查找到的数据...");
        }
        TbkUrlTransferRecord update = new TbkUrlTransferRecord();
        update.setId(record.getId());
        update.setResult(content);
        tbkUrlTransferDao.updateById(update);
    }

    private String getTitle(String content) {
        logger.info("content=" + content);
        logger.info("split result=" + splitContent(content).get(0));
        return splitContent(content).get(0);
    }

    public List<String> splitContent(String content) {
        String[] sps = content.split("#\\|\\|#");
        List<String> spList = new ArrayList<>();
        for (String sp : sps) {
            String trimStr = sp.trim();
            if (StringUtils.isEmpty(trimStr)) {
                continue;
            }
            spList.add(trimStr);
        }
        return spList;
    }
}
